package 多线程.安全.同步代码块;

/**
 * @Projectname java_based
 * @Filename WindowTest3
 * @Author an
 * @Data 2022/7/12 8:04
 * @Description TODO
 */

//使用同步代码块解决继承Thread类的方式的线程安全问题

class Windows3 extends Thread{

    private static int ticket = 100;
    private  static Object object = new Object();

    @Override
    public void run() {
        while(true){
            synchronized (Windows3.class){

                if(ticket > 0){

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(getName() + ":卖票，票号为: " + ticket);
                    ticket--;
                }else{
                    break;
                }
            }

        }
    }
}

public class WindowTest3 {
    public static void main(String[] args) {
        Windows3 t1 = new Windows3();
        Windows3 t2 = new Windows3();
        Windows3 t3 = new Windows3();

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}
